package com.newcapec.modules.oss.cloud;

import com.newcapec.common.exception.RRException;
import io.minio.MinioClient;

import java.io.ByteArrayInputStream;
import java.io.InputStream;

/**
 * 私有云存储
 *
 * @author steven
 */
public class MinioCloudStorageService extends CloudStorageService {
    private MinioClient minioClient;
    private String bucketName;

    public MinioCloudStorageService(CloudStorageConfig config){
        this.config = config;

        //初始化
        init();
    }

    private void init(){
        try {
            minioClient = new MinioClient(config.getMinioDomain(), config.getMinioAccessKey(), config.getMinioSecretKey());
            bucketName = config.getMinioBucketName();
            if (!minioClient.bucketExists(bucketName)) {
                minioClient.makeBucket(bucketName);
            }
        } catch (Exception e) {
            throw new RRException("上传文件失败，请检查配置信息", e);
        }
    }

    @Override
    public String upload(byte[] data, String path) {
        return upload(new ByteArrayInputStream(data), path);
    }

    @Override
    public String upload(InputStream inputStream, String path) {
        try {
            minioClient.putObject(bucketName, path, inputStream, inputStream.available(), "application/octet-stream");
        } catch (Exception e) {
            throw new RRException("上传文件失败", e);
        }
        return "/" + config.getMinioBucketName() + "/" + path;
    }

    @Override
    public String uploadSuffix(byte[] data, String suffix) {
        return upload(data, getPath(config.getQiniuPrefix(), suffix));
    }

    @Override
    public String uploadSuffix(InputStream inputStream, String suffix) {
        return upload(inputStream, getPath(config.getQiniuPrefix(), suffix));
    }
}
